package org.cleverframe.modules.sys.controller;

import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.cleverframe.common.controller.BaseController;
import org.cleverframe.common.persistence.Page;
import org.cleverframe.common.utils.Encodes;
import org.cleverframe.common.vo.AjaxMessage;
import org.cleverframe.core.fileupload.FileuploadBeanNames;
import org.cleverframe.core.fileupload.entity.FileInfo;
import org.cleverframe.core.fileupload.service.IStorageService;
import org.cleverframe.modules.sys.SysBeanNames;
import org.cleverframe.modules.sys.SysJspUrlPath;
import org.cleverframe.modules.sys.entity.TemplateFile;
import org.cleverframe.modules.sys.service.TemplateFileService;
import org.cleverframe.webui.easyui.data.DataGridJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 模版文件实体Controller<br>
 * @author LiZW
 * @version 2015年12月25日 下午3:02:39
 */
@Controller
@RequestMapping("/${mvcPath}/sys")
@Transactional(readOnly = true)
public class TemplateFileController extends BaseController
{
    /** 日志对象 */
    private final static Logger logger = LoggerFactory.getLogger(TemplateFileController.class);
            
    @Autowired
    @Qualifier(SysBeanNames.TemplateFileService)
    private TemplateFileService templateFileService;
    
    @Autowired
    @Qualifier(FileuploadBeanNames.LocalStorageService)
    private IStorageService storageService;
    
    /** 跳转到系统模版管理页面 */
    @RequestMapping("/getTemplateFileJsp")
    public ModelAndView getTemplateFileJsp(HttpServletRequest request, HttpServletResponse response)
    {
        ModelAndView mav = new ModelAndView(SysJspUrlPath.SysTemplateFile);
        return mav;
    }
    
    /** 
     * 查询系统模版数据，使用分页<br>
     * @return EasyUI DataGrid控件的json数据
     *  */
    @ResponseBody
    @RequestMapping("/findTemplateFileByPage")
    public DataGridJson<Map<Object, Object>> findTemplateFileByPage(
            HttpServletRequest request, 
            HttpServletResponse response,
            @RequestParam(value = "name", required = false,defaultValue="") String name,
            @RequestParam(value = "fileName", required = false,defaultValue="") String fileName,
            @RequestParam(value = "id", required = false,defaultValue="-1") Long id,
            @RequestParam(value = "uuid", required = false,defaultValue="") String uuid)
    {
        name = name + "%";
        fileName = fileName + "%";
        DataGridJson<Map<Object, Object>> json = new DataGridJson<Map<Object, Object>>();
        Page<Map<Object, Object>> page = templateFileService.findTemplateFileByPage(new Page<Map<Object, Object>>(request, response), name, fileName, id, uuid);
        json.setRows(page.getList());
        json.setTotal(page.getCount());
        return json;
    }
    
    /**
     * 增加模版文件<br>
     * @return
     */
    @ResponseBody
    @RequestMapping("/addTemplateFile")
    @Transactional(readOnly = false)
    public AjaxMessage addTemplateFile(HttpServletRequest request, HttpServletResponse response, @Valid TemplateFile templateFile, BindingResult bindingResult)
    {
        AjaxMessage message = new AjaxMessage(true);
        if (beanValidator(bindingResult, message))
        {
            if (templateFileService.addTemplateFile(templateFile, message))
            {
                message.setMessage("增加模版成功");
            }
            else
            {
                message.setSuccess(false);
            }
        }
        return message;
    }
    
    /**
     * 更新模版文件<br>
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateTemplateFile")
    @Transactional(readOnly = false)
    public AjaxMessage updateTemplateFile(HttpServletRequest request, HttpServletResponse response, @Valid TemplateFile templateFile, BindingResult bindingResult)
    {
        AjaxMessage message = new AjaxMessage(true);
        if (beanValidator(bindingResult, message))
        {
            if (templateFileService.updateTemplateFile(templateFile, message))
            {
                message.setMessage("更新模版成功");
            }
            else
            {
                message.setSuccess(false);
            }
        }
        return message;
    }
    
    @ResponseBody
    @RequestMapping("/deleteTemplateFile")
    @Transactional(readOnly = false)
    public AjaxMessage deleteTemplateFile(HttpServletRequest request, HttpServletResponse response, @Valid TemplateFile templateFile, BindingResult bindingResult)
    {
        AjaxMessage message = new AjaxMessage(true);
        if (beanValidator(bindingResult, message))
        {
            if (templateFileService.deleteTemplateFile(templateFile, message))
            {
                message.setMessage("删除模版成功");
            }
            else
            {
                message.setSuccess(false);
            }
        }
        return message;
    }
    
    /**
     * 下载模版文件<br>
     * */
    @ResponseBody
    @RequestMapping("/downloadTemplateFile/{fileName}")
    public AjaxMessage downloadTemplateFile(
            HttpServletRequest request, 
            HttpServletResponse response, 
            @PathVariable(value = "fileName") String fileName)
    {
        AjaxMessage message = new AjaxMessage(false);
        FileInfo fileInfo = templateFileService.getTemplateFileByName(fileName);
        if (fileInfo == null)
        {
            message.setMessage("未找到模版信息，请先上传模版，模板文件:" + fileName);
        }
        else
        {
            // 文件存在，下载文件
            String filename = Encodes.browserDownloadFileName(request.getHeader("User-Agent"), fileInfo.getFileName());
            response.setContentType("multipart/form-data");
            // response.setHeader("Content-Disposition", "attachment;");
            response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
            response.setHeader("Content-Length", fileInfo.getFileSize().toString());
            try
            {
                OutputStream outputStream = response.getOutputStream();
                fileInfo = storageService.openFile(fileInfo.getUuid(), outputStream);
                // outputStream.close(); //Servlet容器会关闭
            }
            catch (Exception e)
            {
                logger.info("下载文件取消或失败", e);
            }
            return null;
        }
        return message;
    }
    
    
}
